<template>
    <el-upload
               class="avatar-uploader"
               action="/api/upload/uploadImg"
               :show-file-list="false"
               name="img"
               :on-success="handleAvatarSuccess"
               :before-upload="beforeAvatarUpload">
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon">
            <Plus />
        </el-icon>
    </el-upload>
</template>

<script lang="ts" setup>

import { ref, watchEffect } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

import type { UploadProps } from 'element-plus'



const imageUrl = ref('')

//定义props

let props = defineProps({
    reDisplayImgUrl: {
        type: String,
        default() {
            return null
        }
    }
})


watchEffect(() => {
    // console.log(props.reDisplayImgUrl)
    if (props.reDisplayImgUrl) {
        imageUrl.value = props.reDisplayImgUrl
        // console.log(imageUrl.value)
    } else {
        // image.value.src = ""
        imageUrl.value = ""
    }

}, {
    //dom加载之后再执行
    flush: 'post'
})

//定义自定义的事件

let emit = defineEmits(["transfor-imgurl"])

//上传完毕
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    console.log(response)
    imageUrl.value = URL.createObjectURL(uploadFile.raw!)
    //调用dialog父组件的自定义函数
    if (response.state) {
        emit('transfor-imgurl', response.imgUrl)
    }
}

//文件即将上传
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    // console.log(rawFile.size)
    let rawFileTypeArr = ['image/webp', 'image/jpeg', 'image/png']
    // console.log(rawFile.size.toString())
    //限制文件类型
    if (!rawFileTypeArr.includes(rawFile.type)) {
        ElMessage.error('上传的文件格式,只能是png,jpeg,webp')
        return false
    } else if (rawFile.size / 1024 / 1024 > 1) {

        ElMessage.error('上传图片不能超过2M')
        return false
    }
    return true
}
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
